package com.yn.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.yn.common.enums.*;
import com.yn.common.exception.TransitException;
import com.yn.common.model.user.User;
import com.yn.common.model.zy.*;
import com.yn.common.model.zyorder.ZyOrder;
import com.yn.common.request.sc.LoginMobileRequest;
import com.yn.common.response.driver.*;
import com.yn.service.service.DriverHomeService;
import com.yn.service.service.ICarBillService;
import com.yn.service.service.UserService;
import com.yn.service.service.ZyOrderService;
import com.yn.service.zy.TCarFleetManageService;
import com.yn.service.zy.TCarManageService;
import com.yn.service.zy.TCareforInfoService;
import com.yn.service.zy.TDeviceInfoService;
import io.jsonwebtoken.lang.Collections;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 司机端统计 -- 我的主页 前端控制器
 *
 */
@Service
@Slf4j

public class DriverHomeServiceImpl implements DriverHomeService {
    @Autowired
    private  UserService userService;

    @Autowired
    private  ZyOrderService zyOrderService;
    @Autowired
    private ICarBillService carBillService;

    @Autowired
    private TCarFleetManageService fleetManageService;

    @Autowired
    private TCareforInfoService tCareforInfoService;


    @Override
    public DriverCountResponse count() {
        //获取当前用户id
        User user = userService.getInfoException();
        //TCarManageDO one = tCarManageService.lambdaQuery().eq(TCarManageDO::getAppUserId, user.getUid()).one();
        /*TCarFleetManageDO one = fleetManageService.lambdaQuery()
                .eq(TCarFleetManageDO::getAppUserId, user.getUid())
                .eq(TCarFleetManageDO::getAuditStatus, AuditStatusEnum.PASS.getCode())
                .one();

        if(one== null){
            return  response.setOrderNums(0).setNowMoney(0.0);
        }*/
        DriverCountResponse response = new DriverCountResponse();
        Integer orderNums = zyOrderService.lambdaQuery()
                .eq(ZyOrder::getCarAppUserId, user.getUid())
                .ge(ZyOrder::getOrderStatus, EnumZyOrderStatus.YSD.getCode())
                .count();
        BigDecimal income = user.getIncome();
        if(income == null){
            income = BigDecimal.ZERO;
        }
        response.setOrderNums(orderNums);
        //将BigDecimal转为 double
        response.setNowMoney(income.doubleValue());
        return response;
    }

    @Override
    public DriverBasicInfoResponse getBasicInfo() {
        //获取当前用户信息
        User user = userService.getInfoException();
        String nickname = user.getNickname();
        String phone = user.getPhone();
        String avatar = user.getAvatar();
        if(nickname == null || nickname.isEmpty()){
            nickname = phone;
        }

        DriverBasicInfoResponse response = new DriverBasicInfoResponse();
        String maskedPhone = phone.substring(0, 3) + "****" + phone.substring(7);
        response.setNickName(nickname);
        response.setPhone(maskedPhone);
        response.setAvatar(avatar);
       /* TCarManageDO one = tCarManageService.lambdaQuery().eq(TCarManageDO::getAppUserId, user.getUid()).one();
        if(one==null){
            response.setCarStatus(CarStatusEnum.RESTING.getCode());
        }else{
            response.setCarStatus(one.getCarStatus());
        }*/
        TCarFleetManageDO one = fleetManageService.lambdaQuery()
                .eq(TCarFleetManageDO::getAppUserId, user.getUid())
                .eq(TCarFleetManageDO::getAuditStatus, AuditStatusEnum.PASS.getCode())
                .one();
        if(one==null){
            response.setPostStatus(PostStatusEnum.OUT_OF_SERVICE.getCode());
            response.setPostStatusStr(PostStatusEnum.OUT_OF_SERVICE.getName());
        }else{
            response.setPostStatus(one.getPostStatus());
            response.setPostStatusStr(PostStatusEnum.getByCode(one.getPostStatus()).getName());
        }
        return response;
    }

    @Override
    public void setCarStatus(Integer carStatus) {
        Integer userId = userService.getUserIdException();
        List<TCarFleetManageDO> fleetInfoList = fleetManageService.getInfoByAppUserId(userId);
        if(Collections.isEmpty(fleetInfoList)){
            throw new TransitException("您没有车队信息，设置上岗状态失败");
        }
        fleetInfoList.forEach(one -> {
            one.setPostStatus(carStatus);
        });
        fleetManageService.updateBatchById(fleetInfoList);
    }

    @Override
    public DriverIncomeResponse myIncome() {
        //获取当前用户信息
        User user = userService.getInfoException();
        DriverIncomeResponse response = new DriverIncomeResponse();
        BigDecimal income = user.getIncome();
        if(income == null){
           income = BigDecimal.ZERO;
        }
        response.setIncome(income.doubleValue());
        //只考虑司机，不考虑陪护
        TCarFleetManageDO one = fleetManageService.lambdaQuery()
                .eq(TCarFleetManageDO::getAppUserId, user.getUid())
                .eq(TCarFleetManageDO::getAuditStatus, AuditStatusEnum.PASS.getCode())
                .one();
        if(one == null){
            response.setBillLists(new ArrayList<>());
            return response;
        }
        List<CarBillDO> carBillDOList = carBillService.lambdaQuery().eq(CarBillDO::getCarFleetId, one.getId()).orderByDesc(CarBillDO::getCreateTime).list();
        if(carBillDOList == null || carBillDOList.isEmpty()){
            response.setBillLists(new ArrayList<>());
            return response;
        }
        List<DriverBillList> billLists = new ArrayList<>();
        for (CarBillDO carBillDO : carBillDOList) {
            DriverBillList driverBillList = new DriverBillList();
            BeanUtil.copyProperties(carBillDO, driverBillList);
            billLists.add(driverBillList);
        }
        response.setBillLists(billLists);

        return response;
    }

    @Override
    public BasicInfoResponse myIdentity() {
        //获取当前用户信息
        User user = userService.getInfoException();
        BasicInfoResponse response = new BasicInfoResponse();
        if(Objects.equals(user.getIdentity(), UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode())){
            //车队入住人员
            TCarFleetManageDO one = fleetManageService.lambdaQuery()
                    .eq(TCarFleetManageDO::getAppUserId, user.getUid())
                    .eq(TCarFleetManageDO::getAuditStatus, AuditStatusEnum.PASS.getCode())
                    .eq(TCarFleetManageDO::getIsDelTag, false)
                    .one();
            /*TCarManageDO one = tCarManageService.lambdaQuery()
                    .eq(TCarManageDO::getAppUserId, user.getUid())
                    .eq(TCarManageDO::getAuditStatus,1)//审核通过
                    .one();*/
            if(one==null){
                return null;
            }
            response.setIdentity(UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode());
            response.setIdentityStr(UserIdentityEnum.getByCode(user.getIdentity()).getName());
            response.setSex(user.getSex());
            response.setRealName(user.getRealName());
            response.setCardId(user.getCardId());
            response.setPhone(user.getPhone());
            //因为在添加司机时，需要审核，审核通过会更新update_time，所以这里展示的信息应该是update_time
            response.setAuthTime(DateUtil.format(one.getUpdateTime(), DatePattern.NORM_DATETIME_PATTERN));
        }else if(Objects.equals(user.getIdentity(), UserIdentityEnum.ESCORT_PERSONNEL.getCode())){
            //陪护人员
            TCareforInfoDO one = tCareforInfoService.lambdaQuery().eq(TCareforInfoDO::getAppUserId, user.getUid()).eq(TCareforInfoDO::getAuditStatus, 1).one();
            if(one==null){
                return null;
            }
            response.setIdentity(UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode());
            response.setIdentityStr(UserIdentityEnum.getByCode(user.getIdentity()).getName());
            response.setSex(user.getSex());
            response.setRealName(user.getRealName());
            response.setCardId(user.getCardId());
            response.setPhone(user.getPhone());
            response.setAuthTime(DateUtil.format(one.getUpdateTime(), DatePattern.NORM_DATETIME_PATTERN));
        }else{
            return null;
        }
        return response;
    }

    @Override
    @Transactional
    public void setFleetCarStatus(Integer postStatus) {
        Integer userId = userService.getUserIdException();
        List<TCarFleetManageDO> infoByAppUserId = fleetManageService.getInfoByAppUserId(userId);
        if(Collections.isEmpty(infoByAppUserId)){
            throw new TransitException("您没有车队信息，设置上岗状态失败");
        }
        infoByAppUserId.forEach(one -> {
            one.setPostStatus(postStatus);
        });
        fleetManageService.updateBatchById(infoByAppUserId);
    }

    @Override
    @Transactional
    public void deleteIdentity(Integer carFleetId) {
        //获取当前用户信息
        User user = userService.getInfoException();
        if(!Objects.equals(user.getIdentity(), UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode())){
            throw new TransitException("您没有权限删除该信息");
        }
        //将用户身份改为普通用户
        user.setIdentity(UserIdentityEnum.ORDINARY_USER.getCode());
        userService.updateById(user);
        //删除车队信息
        boolean remove = fleetManageService.removeById(carFleetId);
        if(!remove){
            throw new TransitException("解绑失败");
        }
    }

    /*@Override
    public DriverIncomeResponse myIncome() {
        //获取当前用户信息
        User user = userService.getInfoException();
        DriverIncomeResponse response = new DriverIncomeResponse();
        if(user.getIncome() == null){
            response.setIncome(0.0);
        }
        response.setIncome(user.getIncome().doubleValue());
        //根据用户id查询车辆表
        TCarManageDO one = tCarManageService.lambdaQuery().eq(TCarManageDO::getAppUserId, user.getUid()).one();
        if(one == null){
            response.setZyDriverOrderListResponses(new ArrayList<>());
            return response;
        }
        //根据车辆id查询订单表中该司机的订单状态大于已送达的订单
        List<ZyOrder> zyOrderList = zyOrderService.lambdaQuery()
                .eq(ZyOrder::getCarManageId, one.getId())
                .le(ZyOrder::getOrderStatus, EnumZyOrderStatus.YSD.getCode()).list();
        if(zyOrderList == null || zyOrderList.isEmpty()){
            response.setZyDriverOrderListResponses(new ArrayList<>());
            return response;
        }
        ArrayList<ZyDriverOrderListResponse> responseArrayList = new ArrayList<>(zyOrderList.size());
        for (ZyOrder zyOrder : zyOrderList) {
            ZyDriverOrderListResponse listResponse = new ZyDriverOrderListResponse();
            BeanUtil.copyProperties(zyOrder, listResponse);
            Integer distance = zyOrder.getTransferDistance();
            //将距离转为KM
            Double distance2Db = (distance *100.0/1000)/100;
            listResponse.setTransferDistance(distance2Db);
            responseArrayList.add(listResponse);
        }
        response.setZyDriverOrderListResponses(responseArrayList);

        return response;
    }*/


}
